from django.contrib.auth.models import AbstractUser
from django.core.validators import RegexValidator
from .utils.encryption_utils import encryption_util
from django import forms
from .validators.ValidatePassword import ValidatePassword
from django.db import models

'''
用户名（唯一） username

邮箱（唯一） email

密码（需确认）前端校验 password

地址（可选） attr

手机号码（可选） phone

是否管理员 is_admin
大家不要使用AbstractUser 使用models.Models试试，我的模型不可逆。。。不想在改了 最好 新建main 新建user app
别用这个使用这个其实想用他的默认用户但是没必要 使用了那个模型 还怎么自己理解登录这些信息呢
'''


class User(AbstractUser):
    username = models.CharField(max_length=100, unique=True)
    email = models.EmailField(unique=True)
    password = models.CharField(max_length=100)
    attr = models.CharField(max_length=500)
    phone = models.CharField(max_length=11, unique=True)
    is_admin = models.BooleanField(default=False)
    # 之前我这儿都没有 models.Model是不需要这些的  现在引入了 很无语 不可逆操作 makemigations  所以要不就是删除db.sqllite3再重新使用命令 python manage.py migate
    # 使用 username 作为登录字段
    USERNAME_FIELD = 'username'
    # 创建超级用户时需要填写的字段
    REQUIRED_FIELDS = ['is_admin']
    def __str__(self):
        return "username:" + self.username + " email:" + self.email + " password:" + self.password + " attr:" + self.attr + " phone:" + self.phone
# 用户登录
class UserLoginForm(forms.Form):
    username = forms.CharField(max_length=100, error_messages={
        'required': '用户名不能为空',
        'max_length': '用户名不能超过100个字符'
    })
    password = forms.CharField(validators=[ValidatePassword()])
    def clean(self):
        cleaned_data = super().clean()
        username = cleaned_data.get("username")
        password = cleaned_data.get("password")
        user_count = User.objects.filter(username=username,password=str(encryption_util.hash_password_sha256(password))).count()
        if user_count == 0:
            raise forms.ValidationError("密码错误，请重新输入？")

# 表单校验
class UserRegistrationForm(forms.Form):
    username = forms.CharField(max_length=100, error_messages={
        'required': '用户名不能为空',
        'max_length': '用户名不能超过100个字符'
    })
    password = forms.CharField(validators=[ValidatePassword()])
    confirm_password = forms.CharField(validators=[ValidatePassword()])
    email = forms.CharField(
        label="邮箱",
        max_length=100,
        validators=[
            RegexValidator(
                regex=r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$',
                message="请输入有效的邮箱地址",
            )
        ],
        widget=forms.EmailInput(attrs={'placeholder': 'example@example.com'})
    )

    phone = forms.CharField(validators=[
        RegexValidator(
            regex=r'^1[3-9]\d{9}$',
            message="请输入有效的手机号",
        )
    ])

    def save(self):
        cleaned_data = self.cleaned_data
        user = User(
            username=cleaned_data['username'],
            password=encryption_util.hash_password_sha256(cleaned_data['password']),  # 哈希处理密码
            email=cleaned_data['email'],
            phone=cleaned_data['phone'],
            is_admin=False
        )
        user.save()
        return user

    def clean(self):
        cleaned_data = super().clean()
        username = cleaned_data.get("username")
        user_count = User.objects.filter(username=username).count()
        if user_count > 0:
            raise forms.ValidationError("用户名已被占用，请更换")
        password = cleaned_data.get('password')  # 获取 password 参数
        confirm_password = cleaned_data.get('confirm_password')
        if password and confirm_password and password != confirm_password:
            raise forms.ValidationError("两次输入的密码不匹配")
